package es.prodevelop.arport.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import es.prodevelop.arport.PoiBean;

public class Utils {

	private static List<PoiBean> heritageList = null;
	private static List<PoiBean> leisureList = null;

	public static List<PoiBean> getHeritageList() {
		return heritageList;
	}

	public static List<PoiBean> getLeisureList() {
		return leisureList;
	}

	public static String loadHeritagePoiBeans(Activity activity) {
		if (heritageList == null) {
			heritageList = new ArrayList<PoiBean>();
			List<PoiBean> list = loadPoiBeans(activity, "arport-heritage.json");
			if (list != null) {
				heritageList.addAll(list);
			}
		}
		return new Gson().toJson(heritageList);
	}

	public static String loadLeisurePoiBeans(Activity activity) {
		if (leisureList == null) {
			leisureList = new ArrayList<PoiBean>();
			List<PoiBean> list = loadPoiBeans(activity, "arport-leisure.json");
			if (list != null) {
				leisureList.addAll(list);
			}
		}
		return new Gson().toJson(leisureList);
	}

	private static List<PoiBean> loadPoiBeans(Activity activity, String jsonFile) {
		StringBuilder json = new StringBuilder();

		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					activity.getAssets().open(jsonFile)));
			// do reading, usually loop until end of file reading
			String mLine = reader.readLine();
			while (mLine != null) {
				// process line
				json.append(mLine);
				mLine = reader.readLine();
			}

			reader.close();
		} catch (IOException e) {
			// log the exception
		}

		try {
			Gson gson = new Gson();
			Type type = new TypeToken<List<PoiBean>>() {
			}.getType();
			return gson.fromJson(json.toString(), type);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}
}
